namespace Xmef.Engine
{
    using System;
    using System.Globalization;
    using Xmef.Engine.Internal;
    using Xmef.Interfaces;
    using Xmef.Library;

    [Serializable]
    public class PluginServiceManager : PluginServiceProvider<IPluginService>, IPluginServiceManagerInternal
    {
        private IPluginHostManager _manager;

        public PluginServiceManager(IPluginHostManager manager)
        {
            this._manager = manager;
        }

        public static int CountService<T>(IPluginServiceManager manager) where T: class, IPluginServiceProvider<T>
        {
            if (manager != null)
            {
                return manager.PluginService.Count(typeof(IPluginService<T>));
            }
            return 0;
        }

        public static IPluginService<T> GetService<T>(IPluginServiceManager manager)
        {
            if (manager != null)
            {
                IPluginService<T> item = manager.PluginService.GetItem(typeof(IPluginService<T>), 0) as IPluginService<T>;
                if (item != null)
                {
                    return item;
                }
            }
            return null;
        }

        public static void RegisterService<T>(IPluginServiceManager control, IPluginService<T> service) where T: class, IPluginServiceProvider<T>
        {
            IPluginServiceManagerInternal manager = (IPluginServiceManagerInternal) control;
            if (manager != null)
            {
                manager.RegisterService<T>(service);
            }
        }

        public static void UnregisterService<T>(IPluginServiceManager control, IPluginService<T> service) where T: class, IPluginServiceProvider<T>
        {
            IPluginServiceManagerInternal manager = (IPluginServiceManagerInternal) control;
            if (manager != null)
            {
                manager.UnregisterService<T>(service);
            }
        }

        void IPluginServiceManagerInternal.RegisterService<T>(IPluginService<T> service)
        {
            if ((service != null) && PluginService.Register(typeof(IPluginService<T>), service))
            {
                LogHelper.Write(string.Format(CultureInfo.InvariantCulture, "register service={0}", new object[] { TypeHelper.GetServiceName(service.GetType()) }));
            }
        }

        void IPluginServiceManagerInternal.UnregisterService<T>(IPluginService<T> service)
        {
            if ((service != null) && PluginService.Unregister(typeof(IPluginService<T>), service))
            {
                LogHelper.Write(string.Format(CultureInfo.InvariantCulture, "unregister service={0}", new object[] { TypeHelper.GetServiceName(service.GetType()) }));
            }
        }
    }
}

